package lumis.content.search;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import lumis.doui.search.DouiReindexerTabularDataProcessor;
import lumis.doui.source.ISourceData;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.portal.PortalException;
import lumis.portal.dao.hibernate.ITransactionHibernate;
import lumis.portal.transaction.PortalTransactionFactory;

/**
 * IReindexerTabularDataProcessor implementation for Content services
 *
 * @version $Revision: 8732 $ $Date: 2008-01-08 12:00:58 -0200 (Tue, 08 Jan 2008) $
 * @since 4.0.7
 */
public class ContentReindexerTabularDataProcessor extends DouiReindexerTabularDataProcessor
{
	@SuppressWarnings("unchecked")
	@Override
	public TabularData processTabularData(TabularSource tabularSource, TabularData tabularData)
	{
		tabularData = super.processTabularData(tabularSource, tabularData);
		if (!tabularData.isEmpty())
		{
			Collection<String> itemIds = new ArrayList<String>(tabularData.getRows().size());
			String pkFieldId = tabularSource.getPrimaryKeyField().getId();
			for (ISourceData row: tabularData.getRows())
			{
				itemIds.add(row.get(pkFieldId, String.class));
			}
			
			// remove from tabular data contents not administered by this service instance 
			// (these contents will be indexed when the principal service instance is indexed)
			// and non-published contents
			try
			{
				String serviceInstanceId = tabularSource.getSourceContext().getServiceInstanceConfig().getId();
				Session session = ((ITransactionHibernate)PortalTransactionFactory.getCurrentTransaction()).getSession();
				List<String> acceptedItemIds = session.createQuery("select v.itemId from ContentVersion v where v.itemId in (:itemIds) " + 
						"and v.contentLocale.content.serviceInstanceId = :serviceInstanceId " + 
						"and true = any (select p.published from v.publications p)")
						.setParameterList("itemIds", itemIds)
						.setString("serviceInstanceId", serviceInstanceId)
						.list();
				for(Iterator<ISourceData> iterator = tabularData.getRows().iterator(); iterator.hasNext();)
				{
					ISourceData row = iterator.next(); 
					String itemId = row.get(pkFieldId, String.class);
					if (!acceptedItemIds.contains(itemId))
					{
						iterator.remove();
						continue;
					}
				}
			}
			catch (PortalException e)
			{
				throw new RuntimeException(e);
			}
		}
		
		return tabularData;
	}

}
